<template>
    <div>
        <el-tabs type="border-card" style="width: 100%">
            <!-- 筛选查询条件 -->
            <div style="border: 1px solid lightgray;">
                <div style="width: 100%; height: 50px;background-color: rgb(243, 243, 243);">
                    <span style="position: relative; top: 15px; left: 10px; font: bold 18px '等线';">筛选查询</span>
                </div>
                <div style="height: 40px; position: relative; left: 20px; top: -10px">
                    <!-- 搜索筛选 -->
                    <el-form :inline="true" :model="searchItem" class="user-search">
                        <el-form-item>
                            <el-input :clearable="true" size="large" v-model="searchItem.chain_no" placeholder="链单编号">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input :clearable="true" size="large" v-model="searchItem.scfpUser.name"
                                placeholder="开单人"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-date-picker v-model="value2" type="datetimerange" :picker-options.sync="pickerOptions"
                                range-separator="至" start-placeholder="兑付日起" end-placeholder="兑付日止"
                                value-format="yyyy-MM-dd HH:mm:ss" align="right">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button size="large" type="primary" icon="el-icon-search" @click="search">开始检索
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <!-- 按钮组 -->
            <div>
                <div style="padding-top: 30px; padding-bottom: 15px;">
                    <el-radio-group v-model="type" @change="updateData" fill="rgb(0,191,160)">
                        <el-radio-button label="全部链单">全部链单（<span class="button_group"> {{ allCount }} </span>）
                        </el-radio-button>
                        <el-radio-button label="待兑链单">待兑链单（<span class="button_group"> {{ waitCount }} </span>）
                        </el-radio-button>
                        <el-radio-button label="已兑链单">已兑链单（<span class="button_group"> {{ alreadyCount }} </span>）
                        </el-radio-button>
                    </el-radio-group>
                </div>
            </div>

            <!-- 查询得到的列表信息 -->
            <div style="border: 1px solid lightgray;">
                <div style="width: 100%; height: 50px;background-color: rgb(243, 243, 243);">
                    <el-button @click="batLoan" size="small" style="position:relative; left: 10px; top: 10px">批量兑付所选链单
                    </el-button>
                    <el-button icon="el-icon-download" size="small" @click="exportExcel"
                        style="position:relative; left: 65%; top: 10px">导出当前链单记录</el-button>
                    <el-select size="small" v-model="value" placeholder="排序方式" @change="changeSort(value)"
                        style="width: 130px;position:relative; left: 65%; top: 10px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div>
                    <el-table ref="multipleTable" :row-class-name="tableRowClassName" :data="tableData"
                        tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange"
                        @cell-click="chainDetails">
                        <el-table-column align="center" type="selection" width="55" :selectable='selectEnable'>
                        </el-table-column>
                        <el-table-column align="center" prop="chain_no" label="链单编号" width="220">
                        </el-table-column>
                        <el-table-column align="center" prop="money" label="链单金额" width="150" :formatter="rounding">
                        </el-table-column>
                        <el-table-column align="center" prop="scfpEnterprise.name" label="企业名称" width="150">
                        </el-table-column>
                        <el-table-column align="center" prop="scfpUser.name" label="开单人" width="120"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column align="center" prop="create_time" label="开单日" width="210"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column align="center" prop="deadline" label="兑付日" width="210" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column align="center" fixed="right" label="操作" min-width="140">
                            <template slot-scope="scope">
                                <el-button @click.native.stop="handleClick(scope.row)" type="text" size="small"
                                    v-if="scope.row.status == '18'">兑付
                                </el-button>
                                <el-button type="text" size="small">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="margin-top: 20px; margin-left: 20px;padding-bottom: 20px;float: left;">
                        <el-button type="success" @click="toggleSelection(tableData)">全选/取消全选</el-button>
                    </div>
                    <div style="float:left; position: relative; top: 15px; left: 25%">
                        <!-- 分页组件 -->
                        <Pagination v-bind:child-msg="pageparm" @callFather="callFather">
                        </Pagination>
                    </div>
                </div>
            </div>

        </el-tabs>

        <!-- 兑付界面1 -->
        <el-dialog title="兑付交易" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <p class="loan">兑 付&nbsp;&nbsp;金 额 ：&nbsp;<span style="color: red">{{ dialogData.loan.toFixed(2) }}</span>  RMB</p>
            <p class="loan">兑 付&nbsp;&nbsp;方 式 ：&nbsp;在线交易</p>
            <p class="loan">预计手续费 ：&nbsp;<span style="color: red">{{ (dialogData.loan * 0.0001).toFixed(2) }}</span>  RMB</p>
            <p class="loan">预 计&nbsp;&nbsp;利 息 ：&nbsp;<span style="color: red">{{ (dialogData.loan * 0.01).toFixed(2) }}</span>  RMB</p>
            <!-- <p class="loan">账 户&nbsp;&nbsp;余 额 ：&nbsp;800000.00</p> -->
            <p class="loan">交 易&nbsp;&nbsp;密 码 ：
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                    class="demo-ruleForm">
                    <el-form-item prop="payPass" style="position: relative; top: -40px; left: 5%">
                        <el-input maxlength="6" placeholder="请输入交易密码" show-password style="width:150px"
                            v-model="ruleForm.payPass">
                        </el-input>
                    </el-form-item>
                </el-form>

            </p>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="changeDialog" :disabled="btnChangeEnable">确 定</el-button>
                <el-button @click="dialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>

        <!-- 兑付界面2 -->
        <el-dialog title="兑付交易" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose">
            <el-table v-loading="loading" element-loading-text="正在确认支付结果" :data="tableData"
                style="width: 100%;height: 250px">
            </el-table>
        </el-dialog>

        <!-- 兑付界面3 -->
        <el-dialog title="兑付交易" :visible.sync="dialogVisible3" width="30%" :before-close="handleClose">
            <div style="width: 100%;height: 250px">
                <img src="../../assets/img/success.png" alt="" style="position:relative;top:35%;left:10%;height:100px">
                <span style="position:relative;left:18%;top:18%;font:bold 30px '宋体'; color:green">交 易 成 功</span>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible3 = false">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from "../../components/Pagination";
export default {
    data() {
        var validatePayPass = (rule, value, callback) => {
            if (value === '') {
                this.payPassFlag = false
                callback(new Error('请输入交易密码'));
            }
            else {
                this.payAccount.id = this.enterprise_id
                this.payAccount.pay_pass = this.ruleForm.payPass
                this.$axios.post('/api/chain/checkPayPass', this.payAccount)
                    .then(res => {
                        if (res.data.code == 200) {
                            callback()
                            this.payPassFlag = true
                            this.checkSubmit()
                        } else if (res.data.code == 500) {
                            this.payPassFlag = false
                            callback(new Error('交易密码错误，请重新输入'));
                        }
                    }).catch(err => { })
            }
        };
        return {
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            options: [{
                value: '1',
                label: '链单金额降序 ↓'
            }, {
                value: '2',
                label: '链单金额升序 ↑'
            }, {
                value: '3',
                label: '开单日降序 ↓'
            }, {
                value: '4',
                label: '开单日升序 ↑'
            }, {
                value: '5',
                label: '兑付日降序 ↓'
            }, {
                value: '6',
                label: '兑付日升序 ↑'
            }],
            // 按钮组数据
            recipientList: [
                {
                    label: "全部链单",
                    value: "0"
                },
                {
                    label: "待兑链单",
                    value: "1"
                },
                {
                    label: "已兑链单",
                    value: "2"
                },
            ],
            value: '',
            value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
            value2: '',
            tableData: [],
            multipleSelection: [],
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 5,
                total: 0,
            },
            sortData: {
                enterprise_id: "",
                sortField: "",
                sortType: "",
                currentPage: 1,
                pageSize: 5,
                total: 0,
                chain_no: "",
                scfpUser: {
                    name: "",
                },
                deadline: "",
                deadlineMax: "",
                creator: "",
                status: -1,
                status_tab: "",
            },
            // 条件查询参数
            searchItem: {
                enterprise_id: "",
                chain_no: "",
                scfpUser: {
                    name: "",
                },
                status_tab: "",
                deadline: "",
                deadlineMax: "",
                currentPage: 1,
                pageSize: 5,
                creator: "",
                status: 0,
            },
            // 按钮组查询参数
            buttonItem: {
                enterprise_id: "",
                status: "-1",
                status_tab: "",
                currentPage: 1,
                pageSize: 5,
            },
            type: "全部链单",
            allCount: 0,
            waitCount: 0,
            alreadyCount: 0,
            dialogVisible: false,
            dialogVisible2: false,
            dialogVisible3: false,
            // 弹窗信息
            dialogData: {
                loan: 5000.00,
            },
            // findAllParam参数
            findAllParam: {
                status: 0,
                enterprise_id: "",
                currentPage: 1,
                pageSize: 5,
                total: 0,
            },
            password: "",
            loading: false,
            // 兑付数据(默认全部兑付)
            loanChainId: "",
            ids: [],
            // 全局企业id设置值
            enterprise_id: "",
            chainCount: [
                {
                    status: 18,
                    enterprise_id: "",
                },
                {
                    status_tab: "链单待兑付",
                    enterprise_id: "",
                },
                {
                    status: 19,
                    enterprise_id: "",
                },
            ],
            ruleForm: {
                payPass: '',
            },
            rules: {
                payPass: [
                    { validator: validatePayPass, trigger: 'blur' }
                ],
            },
            payPassFlag: false,
            btnChangeEnable: true,
            // 交易密码参数
            payAccount: {
                id: "",
                pay_pass: "",
            },
            user: {},
        };
    },
    // 注册组件
    components: {
        Pagination,
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
        this.user = JSON.parse(localStorage.getItem('userdata'))
        this.enterprise_id = this.user.enterprise_id
        this.getdata();
        this.findCount();
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
        // 获取公司列表
        getdata() {
            this.type = "全部链单"
            this.findAllParam.status = 18
            this.findAllParam.enterprise_id = this.enterprise_id
            this.$axios.post('/api/chain/findAllLoan', this.findAllParam)
                .then(res => {
                    if (res.data.code == 200) {
                        this.tableData = res.data.data.list
                        // 分页赋值
                        this.pageparm.currentPage = this.pageparm.currentPage
                        //this.pageparm.pageSize = res.data.data.pageSize
                        this.pageparm.total = res.data.data.total
                        this.allCount = res.data.data.total
                    }
                }).catch(err => { })
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleAllSelection();
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
        },
        handleClick(row) {
            this.dialogData.loan = row.money
            this.loanChainId = row.id
            this.dialogVisible = true
        },
        // 分页插件事件
        callFather(parm) {
            if (this.type == "全部链单") {
                this.findAllParam.currentPage = parm.currentPage;
                this.findAllParam.pageSize = parm.pageSize;
                this.getdata();
            } else if (this.type == "待兑链单") {
                this.buttonItem.currentPage = parm.currentPage;
                this.buttonItem.pageSize = parm.pageSize;
                this.updateSearch()
            } else if (this.type == "已兑链单") {
                this.buttonItem.currentPage = parm.currentPage;
                this.buttonItem.pageSize = parm.pageSize;
                this.updateSearch()
            }
            if (this.searchItem.chain_no != "" || this.searchItem.scfpUser.name != "" ||
                this.value2 != "") {
                this.searchItem.currentPage = parm.currentPage
                this.searchItem.pageSize = parm.pageSize;
                this.search()
            }
            if (this.value != "" || this.value != null) {
                this.sortData.currentPage = parm.currentPage
                this.sortData.pageSize = parm.pageSize
                this.changeSort(this.value)
            }
        },
        // 搜索事件
        search() {
            this.type = ""
            this.searchItem.creator = ""
            if ((this.value2 != null && this.value2 != "")) {
                this.searchItem.deadline = this.value2[0]
                this.searchItem.deadlineMax = this.value2[1]
            } else {
                this.searchItem.deadline = ""
                this.searchItem.deadlineMax = ""
            }
            this.searchItem.enterprise_id = this.enterprise_id
            if (this.searchItem.chain_no == "" && this.searchItem.scfpUser.name == "" &&
                (this.value2 == null || this.value2 == "")) {
                this.getdata()
            } else {
                if (this.searchItem.scfpUser.name != "") {
                    this.searchItem.creator = "1"
                } else {
                    this.searchItem.creator = ""
                }
                this.searchItem.status = 18
                this.$axios.post('/api/chain/search', this.searchItem)
                    .then(res => {
                        if (res.data.code == 200) {
                            this.tableData = res.data.data.list
                            // 分页赋值
                            this.pageparm.currentPage = this.pageparm.currentPage
                            //this.pageparm.pageSize = res.data.data.pageSize
                            this.pageparm.total = res.data.data.total
                        }
                    }).catch(err => { })
            }
        },
        // 按钮组事件
        updateData(label) {
            if (label == "全部链单") {
                this.searchItem.chain_no = ""
                this.searchItem.scfpUser.name = ""
                this.searchItem.deadline = ""
                this.searchItem.deadlineMax = ""
                this.getdata()
            } else if (label == "待兑链单") {
                this.buttonItem.status_tab = "链单待兑付"
                this.buttonItem.status = 18
                this.updateSearch()
            } else if (label == "已兑链单") {
                this.findAllParam.status = 19
                this.findAllParam.enterprise_id = this.enterprise_id
                this.$axios.post('/api/chain/findAllLoan', this.findAllParam)
                    .then(res => {
                        if (res.data.code == 200) {
                            this.tableData = res.data.data.list
                            // 分页赋值
                            this.pageparm.currentPage = this.pageparm.currentPage
                            this.pageparm.total = res.data.data.total
                        }
                    }).catch(err => { })
            }

        },
        updateSearch() {
            this.buttonItem.enterprise_id = this.enterprise_id
            this.$axios.post('/api/chain/search', this.buttonItem)
                .then(res => {
                    if (res.data.code == 200) {
                        this.tableData = res.data.data.list
                        // 分页赋值
                        this.pageparm.currentPage = this.pageparm.currentPage
                        //this.pageparm.pageSize = res.data.data.pageSize
                        this.pageparm.total = res.data.data.total
                    }
                }).catch(err => { })
        },
        // 选择排序方式
        changeSort(index) {
            this.sortData.creator = ""
            if (index == 1 || index == 3 || index == 5) {
                this.sortData.sortType = "desc";
            }
            if (index == 2 || index == 4 || index == 6) {
                this.sortData.sortType = "asc";
            }
            if (index == 1 || index == 2) {
                this.sortData.sortField = "money";
            }
            if (index == 3 || index == 4) {
                this.sortData.sortField = "create_time";
            }
            if (index == 5 || index == 6) {
                this.sortData.sortField = "deadline";
            }

            this.sortData.enterprise_id = this.enterprise_id
            this.sortData.status = -1
            this.sortData.scfpUser.name = this.searchItem.scfpUser.name
            this.sortData.chain_no = this.searchItem.chain_no
            this.sortData.deadline = this.searchItem.deadline
            this.sortData.deadlineMax = this.searchItem.deadlineMax
            if (this.type == "全部链单") {
                this.sortData.status_tab = ""
                this.sortData.status = -2
            } else if (this.type == "待兑链单") {
                this.sortData.status_tab = "链单待兑付"
            } else if (this.type == "已兑链单") {
                this.sortData.status_tab = "链单兑付完成"
            }
            if ((this.sortData.chain_no == null || this.sortData.chain_no == "") &&
                (this.sortData.scfpUser.name == null || this.sortData.scfpUser.name == "") &&
                (this.sortData.deadline == null || this.sortData.deadline == "") &&
                (this.sortData.deadlineMax == null || this.sortData.deadlineMax == "")) {
                this.sortData.status = 18
                this.$axios.post('/api/chain/search', this.sortData)
                    .then(res => {
                        if (res.data.code == 200) {
                            this.tableData = res.data.data.list
                            // 分页赋值
                            this.pageparm.currentPage = this.pageparm.currentPage
                            //this.pageparm.pageSize = res.data.data.pageSize
                            this.pageparm.total = res.data.data.total
                        }
                    }).catch(err => { })
            } else {
                this.sortData.status = -2
                if (this.searchItem.scfpUser.name != "") {
                    this.sortData.creator = "1"
                }
                this.sortData.scfpUser.name = this.searchItem.scfpUser.name
                if ((this.value2 != null && this.value2 != "")) {
                    this.searchItem.deadline = this.value2[0]
                    this.searchItem.deadlineMax = this.value2[1]
                } else {
                    this.searchItem.deadline = ""
                    this.searchItem.deadlineMax = ""
                }
                this.$axios.post('/api/chain/search', this.sortData)
                    .then(res => {
                        if (res.data.code == 200) {
                            this.tableData = res.data.data.list
                            // 分页赋值
                            this.pageparm.currentPage = this.pageparm.currentPage
                            //this.pageparm.pageSize = res.data.data.pageSize
                            this.pageparm.total = res.data.data.total
                        }
                    }).catch(err => { })
            }

        },
        // 导出Excel
        exportExcel() {
            var form = document.createElement("form");
            form.style.display = "none";
            form.action = '/api/chain/export';
            form.method = "post";
            document.body.appendChild(form);
            var input = document.createElement("input");
            input.type = "hidden";
            input.name = "json";
            if (this.searchItem.chain_no == "" && this.searchItem.scfpUser.name == "" &&
                (this.value2 == null || this.value2 == "")) {
                this.findAllParam.status = 18
                this.findAllParam.enterprise_id = this.enterprise_id
                input.value = window.JSON.stringify(this.findAllParam);
            } else {
                input.value = window.JSON.stringify(this.searchItem);
            }

            form.appendChild(input);
            form.submit();
            form.remove();
        },
        // 查找各状态链单数量
        findCount() {
            this.chainCount[0].enterprise_id = this.enterprise_id
            this.chainCount[1].enterprise_id = this.enterprise_id
            this.chainCount[2].enterprise_id = this.enterprise_id
            this.$axios.post('/api/chain/findCount', this.chainCount[1])
                .then(res => {
                    if (res.data.code == 200) {
                        this.waitCount = res.data.data
                    }
                }).catch(err => { })
            this.$axios.post('/api/chain/findLoanCount', this.chainCount[2])
                .then(res => {
                    if (res.data.code == 200) {
                        this.alreadyCount = res.data.data
                    }
                }).catch(err => { })
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        // 执行兑付操作后更新兑付数据
        updateLoan() {
            /*
            this.$axios.put('/api/chain/updateLoan/' + this.loanChainId)
                .then(res => {
                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: "兑付成功"
                        })
                    }
                }).catch(err => { })
            */
           this.$axios.post("/api/loan/apply",{
               chain_id:this.loanChainId
           }).then(res=>{
            this.loading = false
            this.dialogVisible2 = false
            if(res.data.code == 200){
                this.$message.success("兑付成功，前往兑付记录可查看！")
                this.dialogVisible3 = true
                this.getdata()
                this.findCount()
            }else{
                // this.dialogVisible = true
                this.$message.error(res.data.message+"兑付失败")
            }
           }).catch(()=>{
               this.$message.error("兑付失败，请稍后再试！")
           })
        },
        // 批处理执行兑付操作
        updateBatLoan() {
            /*
            this.$axios.put('/api/chain/updateBatLoan', this.ids)
                .then(res => {
                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: "兑付成功"
                        })
                    }
                }).catch(err => { })
            */
        },
        //确认兑付
        changeDialog() {
            this.dialogVisible = false
            this.dialogVisible2 = true
            this.loading = true
            if (this.loanChainId != "") {
                this.updateLoan()
            } else {
                this.updateBatLoan()
            }
        },
        // 表格部分信息可选
        selectEnable(row) {
            if (row.status == '18') {
                return true
            }
        },
        // 兑付批处理
        batLoan() {
            this.ids = []
            this.dialogData.loan = 0
            for (let i = 0; i < this.multipleSelection.length; i++) {
                this.dialogData.loan += this.multipleSelection[i].money
                this.ids.push(this.multipleSelection[i].id)
            }
            if (this.dialogData.loan == 0) {
                this.$alert('请至少勾选一个链单！！！', '警告', {
                    confirmButtonText: '确定',
                    type: 'warning',
                    center: true
                })
            } else {
                this.loanChainId = ""
                this.dialogVisible = true
            }
        },
        // 设置表格小数
        rounding(row, column) {
            return parseFloat(row[column.property]).toFixed(2)
        },
        // 设置交易按钮可用状态
        checkSubmit() {
            if (this.payPassFlag == true) {
                this.btnChangeEnable = false
            }
        },
        // 跳转到对应链单详情页
        chainDetails(row) {
            this.$router.push({ path: '/chain/detail', query: { chain_id: row.id } })
        },
        tableRowClassName({ row }) {
            if (row.status >= 19) {
                return 'success-row';
            }
            return 'warning-row';
        },

    },
};
</script>

<style>
.user-search {
    margin-top: 20px;
}

.userRole {
    width: 100%;
}

.button_group {
    color: red;
    font-weight: bold;
    font-size: 16px;
}

.loan {
    margin-left: 20%;
    font: bold 18px 'Times New Roman', '黑体';
    line-height: 40px;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #e3ffd5;
}
</style>

 
 